package ops.controller;

import ops.WindowManager;
import ops.model.EntityAlreadyExistsException;
import ops.model.Subject;
import ops.model.manager.EntityController;
import ops.model.manager.SubjectManager;
import ops.view.SubjectRegisterPanel;

public class SubjectController {
	
	private SubjectManager subjectManager;	
	
	private boolean adding;

	public SubjectController() {
		subjectManager = EntityController.getInstance().getSubjectManager();
	}

	public void startAddProcess() {
		adding = true;
	}
	
	public void endAddProcess() {
		adding = false;
	}
	
	private void add(String name, Integer credits) {
		Integer code = subjectManager.nextIntID();
		
		Subject subject = new Subject();
		subject.setCode(code);
		subject.setName(name);
		subject.setCredits(credits);
		
		try {
			subjectManager.add(subject);
			
			subjectManager.save();
		} catch (EntityAlreadyExistsException e) {
			e.printStackTrace();
		}
	}
	
	private void edit(int code, String name, Integer credits) {
		Subject subject = subjectManager.getObjectByKey(code);		
		subject.setName(name);
		subject.setCredits(credits);
		
		subjectManager.save();
	}
	
	public void saveSubject(Integer code, String name, Integer credits) {
		if (adding) {
			add(name, credits);
			
			adding = false;
		} else {
			edit(code, name, credits);
		}
		
		updateTable();
	}
	
	public void removeSubject(int code) {
		subjectManager.remove(code);
		subjectManager.save();
		
		updateTable();
	}
	
	public void updateTable() {
		SubjectRegisterPanel panel = getPanel();
		
		panel.clearTable();
		
		for (Subject subject : subjectManager.getMap().values()) {
			panel.addRowToTable(subject.getCode(), subject.getName(), subject.getCredits());
		}
	}
	
	private SubjectRegisterPanel getPanel() {
		return (SubjectRegisterPanel) WindowManager.getInstance().getPanel("register.subjects");
	}
}
